<?php

/**
 * Description of Offer
 *
 * @author Kam
 */
class Application_Model_DAO_OfferTemplate extends My_DAO_Abstract {

    const DB_OFFER_TEMPLATE = 'OfferTemplate';
    const DB_OFFER_TEMPLATE_ATTRIBUTES = 'OfferTemplateAttributes';
    
    public function addNew($categoryId, array $attributes, $updateCategory = true) {
        $tpl = array(
            'display' => 'Szablon '.  date(My_Db_Table::DATE_TIME_PATTERN)
        );
        $tplId = $this->getDbTable()->insert($tpl);
        $tpl['offer_template_id'] = $tplId;
        
        $order = 1;
        foreach ($attributes as $attr) {
            $this->setSafety($attr, $attr, 'css');
            if(empty($attr['order'])) {
                $attr['order'] = $order;
            }
            $attr['offer_template_id'] = $tplId;
            $this->getDbTable(self::DB_OFFER_TEMPLATE_ATTRIBUTES)->insert($attr);
            $order++;
        }
        
        // update kategorii
        if($updateCategory) {
            $daoCategory = new Application_Model_DAO_Category();
            $daoCategory->getDbTable()->update(array('offer_template_id' => $tplId), $categoryId);
        }
        $tpl['attributes'] = $attributes;
        return $tpl;
    }


    public function getTemplate($templateId) {
        $tpl = $this->getDbTable()->get($templateId);
        if(empty($tpl)) {
            return null;
        }
        $att = $this->getDbTable()->getTemplateAttributes($templateId)
                ->query()->fetchAll();
        if(empty($att)) {
            $att = array();
        }
        $tpl['attributes'] = $att;
        return $tpl;
    }

    protected function getDbTableNameMap() {
        return array(
            self::DB_OFFER_TEMPLATE => 'Application_Model_DbTable_OfferTemplate',
            self::DB_OFFER_TEMPLATE_ATTRIBUTES => 'Application_Model_DbTable_OfferTemplateAttribute',
        );
    }

    protected function getDefaultDbTableName() {
        return self::DB_OFFER_TEMPLATE;
    }

}
